import { Module } from "vuex";
import { RootState } from "/@/store";
import authCache from "/@/utils/cache/authCache";
import router from "/@/router";
import { firstCharToUpper } from "/@/utils/common";
import { useI18n } from "/@/locales/useI18n";
import { RouteRecordRaw } from "vue-router";
import menuData from "./menuData.json";

interface ApplicationInfo {
  id: string | number;
  name: string;
  url: string;
}

interface RouteMenuItem {
  name: string;
  key?: string;
  action?: string;
  children?: RouteMenuItem[] | null;
  icon?: string;
}

export interface MenuState {
  routeMenuData: RouteMenuItem[];
  restrictPath: string[];
  applicationData: ApplicationInfo[];
  routeTabs: any;
}

function searchAction(result: string[], data: RouteMenuItem[]) {
  data.forEach((el) => {
    if (el.action) {
      result.push(el.action);
    }
    if (el.children) {
      searchAction(result, el.children);
    }
  });
}

const user: Module<MenuState, RootState> = {
  namespaced: true,
  state: () => ({
    routeMenuData: [],
    restrictPath: [],
    applicationData: [],
    routeTabs: null,
  }),
  mutations: {
    setRouteMenuData(state, data) {
      state.routeMenuData = data;
      const actions: string[] = [];
      searchAction(actions, data);
      state.restrictPath = actions;
    },
    setApplicationData(state, data) {
      state.applicationData = data;
    },
    setRouteTabs(state, routeTabs) {
      state.routeTabs = routeTabs;
    },
  },
  actions: {
    async initAuthMenu({ commit }, payload) {
      const userInfo = authCache.getUserInfo();
      if (!userInfo) return [];
      const { rootRouteName } = payload;
      const { t } = useI18n();
      const authMenuData = menuData;
      if (!authMenuData) return null;
      const routeMenuData: RouteMenuItem[] = [];
      const routeData: RouteRecordRaw[] = [];
      authMenuData.sort((a, b) => {
        const v1 = a.sortValue || 0;
        const v2 = b.sortValue || 0;
        return v1 - v2;
      });
      authMenuData.forEach((item) => {
        const { children, name } = item;
        const routeMenu: RouteMenuItem = {
          name: t(`home.${name}`),
          key: name,
          icon: item.icon,
          children: [],
        };
        if (children && children.length > 0) {
          children.sort((a, b) => {
            const v1 = a.sortValue || 0;
            const v2 = b.sortValue || 0;
            return v1 - v2;
          });
          children.forEach((subItem) => {
            const route: RouteRecordRaw = {
              path: `${name}/${subItem.name}`,
              name: subItem.name,
              component: () => import(`../../views/${rootRouteName}/${name}/${firstCharToUpper(subItem.name)}.vue`),
              meta: {
                title: t(`home.${subItem.name}`),
              },
            };
            router.addRoute(rootRouteName, route);
            routeData.push(route);
            (routeMenu.children as RouteMenuItem[]).push({
              name: t(`home.${subItem.name}`),
              key: subItem.name,
              icon: subItem.icon,
              action: `/${rootRouteName}/${name}/${subItem.name}`,
            });
          });
        } else {
          //没有二级菜单的根菜单 视为可打开页面的菜单
          routeMenu.children = null;
          routeMenu.action = `/${rootRouteName}/${name}`;
          const route: RouteRecordRaw = {
            path: `${name}`,
            name,
            component: () => import(`../../views/${rootRouteName}/${firstCharToUpper(name)}.vue`),
            meta: {
              title: t(`home.${name}`),
            },
          };
          router.addRoute(rootRouteName, route);
          routeData.push(route);
        }
        routeMenuData.push(routeMenu);
      });
      commit("setRouteMenuData", routeMenuData);
      return { routeData, routeMenuData };
    },
    /**
     * 查询当前租户的所有授权了的应用信息
     * @returns 应用列表
     */
    async getApplicationsByCurTenant({ commit }) {
      const data = [
        {
          id: 1,
          name: "manage",
          url: "/manage",
        },
      ];
      commit("setApplicationData", data || []);
      return data;
    },
    setRouteTabs({ commit }, routeTabs) {
      commit("setRouteTabs", routeTabs);
    },
    removeTabs({ state }) {
      if (state.routeTabs) {
        state.routeTabs.remove();
      }
    },
  },
};
export default user;
